import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import { WalletManager, WalletAccount } from '../core/WalletManager';
import { NetworkManager } from '../core/NetworkManager';
import { TokenManager } from '../core/TokenManager';

const Container = styled.div`
  width: 400px;
  height: 600px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
`;

const Header = styled.div`
  padding: 20px;
  color: white;
  text-align: center;
`;

const Title = styled.h1`
  margin: 0;
  font-size: 24px;
  font-weight: 600;
`;

const Subtitle = styled.p`
  margin: 5px 0 0 0;
  font-size: 14px;
  opacity: 0.8;
`;

const Content = styled.div`
  flex: 1;
  background: white;
  border-radius: 20px 20px 0 0;
  padding: 20px;
  overflow-y: auto;
`;

const TabContainer = styled.div`
  display: flex;
  margin-bottom: 20px;
  border-bottom: 1px solid #e0e0e0;
`;

const Tab = styled.button<{ active: boolean }>`
  flex: 1;
  padding: 12px;
  border: none;
  background: none;
  font-size: 16px;
  font-weight: 500;
  color: ${props => props.active ? '#667eea' : '#666'};
  border-bottom: 2px solid ${props => props.active ? '#667eea' : 'transparent'};
  cursor: pointer;
  transition: all 0.2s ease;
`;

const Button = styled.button`
  width: 100%;
  padding: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: transform 0.2s ease;
  
  &:hover {
    transform: translateY(-1px);
  }
  
  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
    transform: none;
  }
`;

const Input = styled.input`
  width: 100%;
  padding: 12px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  font-size: 14px;
  margin-bottom: 10px;
  
  &:focus {
    outline: none;
    border-color: #667eea;
  }
`;

const AccountCard = styled.div`
  background: #f8f9fa;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  border: 1px solid #e0e0e0;
`;

const AccountName = styled.h3`
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
`;

const AccountAddress = styled.p`
  margin: 0 0 8px 0;
  font-size: 12px;
  color: #666;
  font-family: monospace;
`;

const Balance = styled.p`
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
`;

const NetworkInfo = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  background: #f0f0f0;
  border-radius: 8px;
  margin-bottom: 20px;
`;

const NetworkName = styled.span`
  font-weight: 500;
`;

const NetworkStatus = styled.span<{ connected: boolean }>`
  color: ${props => props.connected ? '#4caf50' : '#f44336'};
  font-size: 12px;
`;

export const WalletPopup: React.FC = () => {
  const [activeTab, setActiveTab] = useState<'wallet' | 'send' | 'receive' | 'settings'>('wallet');
  const [walletManager] = useState(() => new WalletManager());
  const [networkManager] = useState(() => new NetworkManager());
  const [tokenManager] = useState(() => new TokenManager());
  const [accounts, setAccounts] = useState<WalletAccount[]>([]);
  const [currentAccount, setCurrentAccount] = useState<WalletAccount | null>(null);
  const [isUnlocked, setIsUnlocked] = useState(false);
  const [password, setPassword] = useState('');
  const [sendTo, setSendTo] = useState('');
  const [sendAmount, setSendAmount] = useState('');
  const [isConnected, setIsConnected] = useState(false);

  useEffect(() => {
    loadAccounts();
    checkNetworkConnection();
  }, []);

  const loadAccounts = async () => {
    const accountsList = walletManager.getAccounts();
    setAccounts(accountsList);
    
    const current = walletManager.getCurrentAccount();
    setCurrentAccount(current);
    setIsUnlocked(!!current);
  };

  const checkNetworkConnection = async () => {
    const connected = await networkManager.checkNetworkConnection();
    setIsConnected(connected);
  };

  const handleUnlock = async () => {
    if (!currentAccount) return;
    
    const success = await walletManager.unlockWallet(currentAccount.address, password);
    if (success) {
      setIsUnlocked(true);
      setPassword('');
      loadAccounts();
    } else {
      alert('密码错误');
    }
  };

  const handleSend = async () => {
    if (!isUnlocked || !sendTo || !sendAmount) return;
    
    try {
      const txHash = await walletManager.sendTransaction(sendTo, sendAmount, password);
      alert(`交易已发送: ${txHash}`);
      setSendTo('');
      setSendAmount('');
    } catch (error) {
      alert('发送失败: ' + error.message);
    }
  };

  const renderWalletTab = () => (
    <div>
      {!isUnlocked ? (
        <div>
          <h3>解锁钱包</h3>
          <Input
            type="password"
            placeholder="输入密码"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
          <Button onClick={handleUnlock}>解锁</Button>
        </div>
      ) : (
        <div>
          <NetworkInfo>
            <NetworkName>{networkManager.getCurrentNetwork().name}</NetworkName>
            <NetworkStatus connected={isConnected}>
              {isConnected ? '已连接' : '未连接'}
            </NetworkStatus>
          </NetworkInfo>
          
          {currentAccount && (
            <AccountCard>
              <AccountName>{currentAccount.name}</AccountName>
              <AccountAddress>{currentAccount.address}</AccountAddress>
              <Balance>{currentAccount.balance} ETH</Balance>
            </AccountCard>
          )}
          
          <Button onClick={() => setIsUnlocked(false)}>锁定钱包</Button>
        </div>
      )}
    </div>
  );

  const renderSendTab = () => (
    <div>
      <h3>发送代币</h3>
      <Input
        placeholder="接收地址"
        value={sendTo}
        onChange={(e) => setSendTo(e.target.value)}
      />
      <Input
        placeholder="金额"
        value={sendAmount}
        onChange={(e) => setSendAmount(e.target.value)}
      />
      <Button onClick={handleSend} disabled={!isUnlocked}>
        发送
      </Button>
    </div>
  );

  const renderReceiveTab = () => (
    <div>
      <h3>接收代币</h3>
      {currentAccount && (
        <div>
          <p>您的地址:</p>
          <AccountAddress>{currentAccount.address}</AccountAddress>
          <Button onClick={() => {
            navigator.clipboard.writeText(currentAccount!.address);
            alert('地址已复制到剪贴板');
          }}>
            复制地址
          </Button>
        </div>
      )}
    </div>
  );

  const renderSettingsTab = () => (
    <div>
      <h3>设置</h3>
      <Button onClick={() => {
        chrome.tabs.create({ url: 'chrome://extensions/' });
      }}>
        管理扩展
      </Button>
    </div>
  );

  return (
    <Container>
      <Header>
        <Title>QKL钱包</Title>
        <Subtitle>安全便捷的区块链钱包</Subtitle>
      </Header>
      
      <Content>
        <TabContainer>
          <Tab 
            active={activeTab === 'wallet'} 
            onClick={() => setActiveTab('wallet')}
          >
            钱包
          </Tab>
          <Tab 
            active={activeTab === 'send'} 
            onClick={() => setActiveTab('send')}
          >
            发送
          </Tab>
          <Tab 
            active={activeTab === 'receive'} 
            onClick={() => setActiveTab('receive')}
          >
            接收
          </Tab>
          <Tab 
            active={activeTab === 'settings'} 
            onClick={() => setActiveTab('settings')}
          >
            设置
          </Tab>
        </TabContainer>
        
        {activeTab === 'wallet' && renderWalletTab()}
        {activeTab === 'send' && renderSendTab()}
        {activeTab === 'receive' && renderReceiveTab()}
        {activeTab === 'settings' && renderSettingsTab()}
      </Content>
    </Container>
  );
};
